package com.istock.union.user.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.istock.base.cache.DeleteCache;
import com.istock.base.cache.UseCache;
import com.istock.base.common.api.model.PageInfo;
import com.istock.union.user.dao.TenantInfoMapper;
import com.istock.union.user.model.TenantInfo;
import com.istock.union.user.model.TenantInfoExample;
import com.istock.union.user.service.TenantInfoService;

@Repository
public class TenantInfoServiceImpl implements TenantInfoService{

	@Autowired
	private TenantInfoMapper tenantInfoMapper;
	
	public List<TenantInfo> findTanantList(TenantInfo tenantInfo, PageInfo<TenantInfo> page) {
		TenantInfoExample example = new TenantInfoExample();
		TenantInfoExample.Criteria criteria = example.createCriteria();
		if(tenantInfo != null){
			if(StringUtils.isNotBlank(tenantInfo.getTenantName())){
				criteria.andTenantNameLike("%"+tenantInfo.getTenantName()+"%");
			}
			if(StringUtils.isNotBlank(tenantInfo.getTenantCode())){
				criteria.andTenantCodeEqualTo(tenantInfo.getTenantCode());
			}
			if(tenantInfo.getStatus() != null) {
				criteria.andStatusEqualTo(tenantInfo.getStatus());
			}
		}
		return tenantInfoMapper.selectByExample(example, page);
	}
	
	@UseCache(key="ALL_TENANT_LIST" , expireTime = 30*60 )
	public List<TenantInfo> findAllTenantList(){
		return tenantInfoMapper.selectByExample( new TenantInfoExample());
	}
	
	@DeleteCache(key="ALL_TENANT_LIST")
	public void saveTenantInfo(TenantInfo tenantInfo) {
		if(tenantInfo != null){
			tenantInfo.setCreateTime(new Date());
			if(StringUtils.isNotBlank(tenantInfo.getId())){
				//update
				tenantInfoMapper.updateByPrimaryKeySelective(tenantInfo);
			}else {
				tenantInfoMapper.insertSelective(tenantInfo);
			}
		}
	}

	public TenantInfo findTenantInfoByCode(String tenantCode) {
		if(StringUtils.isNotBlank(tenantCode)) {
			TenantInfoExample example = new TenantInfoExample();
			TenantInfoExample.Criteria criteria = example.createCriteria();
			criteria.andTenantCodeEqualTo(tenantCode);
			List<TenantInfo> tenantList = tenantInfoMapper.selectByExample(example);
			
			if(tenantList != null && tenantList.size()>0) {
				return tenantList.get(0);
			}
		}
		return null;
	}
	
	public TenantInfo findTenantInfoById(String id) {
		return tenantInfoMapper.selectByPrimaryKey(id);
	}
}
